from database.database import Database
from model.dbmodel import DbTask


class TaskTable(Database):
    def __init__(self):
        self.table_name = "tasks"

    def insert(self, data: DbTask):
        sql = self.get_insert_sql_from_obj(data, self.table_name)
        self.execute(sql)
        return int(self.cursor.lastrowid)

    def query(self, id: int) -> DbTask:
        sql = f"select * from {self.table_name} where `id` = {id}"
        self.execute(sql)
        result = self.cursor.fetchone()
        if not result:
            return None
        return DbTask().load(result)

    def update_status(self, id, status: int):
        sql = f"update {self.table_name} set `status` = {status} where `id` = {id}"
        self.execute(sql)

    def restart(self, commit=False):
        sql = f"update {self.table_name} set `status` = 4 where `status` = 1"
        self.execute(sql)
        if commit:
            self.commit()
        return self.cursor.fetchall()

    def get_running_tasks(self):
        sql = f"select * from {self.table_name} where `status` = 1 or `status` = 4"
        self.execute(sql)
        return self.cursor.fetchall()
